package com.senseuni.da.worker

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.elvishew.xlog.XLog
import com.senseuni.da.db.AppDatabase
import com.senseuni.da.http.ApiDataSource

class AppLogWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {

    private val appLogDao by lazy { AppDatabase.getInstance().appLogDao() }

    override suspend fun doWork(): Result {
        XLog.d("AppLogWorker started")
        while (true) {
            if (!doUpload()) {
                break
            }
        }
        XLog.d("AppLogWorker finished")
        return Result.success()
    }

    private suspend fun doUpload() : Boolean{
        val logs = appLogDao.findLogs()
        if (logs.isEmpty()) {
            return false
        }

        val ids = logs.map  { it.id }
        appLogDao.updateStatus(ids, 1 )
        try {
            val response = ApiDataSource.instance.applog(logs)
            if (response.isSuccess) {
                appLogDao.updateSuccess(ids, System.currentTimeMillis())
            } else {
                appLogDao.updateFail(ids, response.codeAndMessage)
                XLog.e("worker.upload device log fail:%s", response.codeAndMessage)
            }
        } catch (e: Exception) {
            appLogDao.updateFail(ids, e.message?: "request failed")
            XLog.e("worker.upload device log fail:%s", e.message)
        }
        return true
    }
}